package com.bjsxt.userscenter.common.util;

import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 加密相关的工具类
 * @author wangshSxt
 *
 */
public class EncryptUtil
{
	/**
	 * 加密
	 * 
	 * 密文:加密算法$随机数$加密(加密算法$随机数$明文)
	 * md5$abcd$md5(md5$abcd$11111)
	 * sha256$abcd$md5(sha256$abcd$11111)
	 * 
	 * @param pass	明文
	 * @return	密文
	 */
	public static String encodeStr(String pass)
	{
		RegexUtil regexUtil = new RegexUtil();
		/* 加密 */
		String encType = "sha256";
		String randStr = regexUtil.proccedStr(32) ;
		/* 加密前置字符串 (md5$abcd$)*/
		String encStr = encType + "$" + randStr + "$";
		/* 加密前串 md5$abcd$11111*/
		String encHead = encStr + pass;
		/* 明文加密 */
		String encBack = DigestUtils.sha256Hex(encHead);
		/* md5$abcd$md5(md5$abcd$11111) */
		return encStr + encBack ; 
	}
	
	/**
	 * 比较两个密码是否一样,重新走一遍加密的流程,比较密文
	 * sha256$p112mh8nzb177odj79ew5ihoubr7r5zz$e70bb37e6caa0fc8b6106f7e343f8467e93e2868f4263ab65215238724094321
	 * 
	 * @param souPass	明文
	 * @param encPass	加密
	 * @return
	 */
	public static boolean checkPass(String souPass,String encPass)
	{
		String[] encPassEs = encPass.split("\\$");
		//System.out.println("数组:" + Arrays.toString(encPassEs));
		/* 加密前置字符串 (md5$abcd$)*/
		String encStr = encPassEs[0] + "$" + encPassEs[1] + "$";
		/* 加密前串 md5$abcd$11111*/
		String encHead = encStr + souPass;
		/* 明文加密 */
		String encBack = DigestUtils.sha256Hex(encHead);
		encBack = encStr + encBack ; 
		return encBack.equals(encPass) ; 
	}
	
	public static void main(String[] args)
	{
		String souPass = "test";
		String result = DigestUtils.md5Hex(souPass);
		System.out.println("md5:"+result);
		
		result = DigestUtils.sha256Hex(souPass);
		System.out.println("sha256Hex:" + result);
		
		result = DigestUtils.sha512Hex(souPass);
		System.out.println("sha512Hex:" + result);
		
		EncryptUtil encryptUtil = new EncryptUtil();
		
		result = encryptUtil.encodeStr(souPass);
		System.out.println("mySalt:" + result);
		
		boolean flag = encryptUtil.checkPass("222222", result);
		System.out.println("检验结果:" + flag);
	}
}
